package org.changs.message.push;

import android.content.Context;
import android.util.Log;

import com.iot.push.sdk.ClientTypeEnum;
import com.iot.push.sdk.IoTCommunicationClient;
import com.iot.push.sdk.message.Audience;
import com.iot.push.sdk.message.Message;
import com.iot.push.sdk.message.MetaInfo;

import org.changs.aplug.base.BasePresenter;
import org.changs.aplug.base.IView;
import org.changs.aplug.utils.AppUtils;
import org.changs.aplug.utils.DeviceUtils;
import org.changs.aplug.utils.JsonUtils;
import org.changs.aplug.utils.NetworkUtils;
import org.changs.message.PushMsg;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import aplug.data.DataManager;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 推送初始化设置
 * Created by Administrator on 2017/4/26.
 */

public class IotPushPresenter extends BasePresenter<IotPushPresenter.V> {

    public interface V extends IView {
        void getMsgList(List<PushMsg> pushMsgs);
    }

    private final DataManager dataManager;
    private ConnectEvent connectEvent;
    private ClientReceiver receiver;
    private String appId;
    private String appSecret;
    private String clientId;
    private List<String> tags;
    private List<String> groups;
    private String alias;
    private LocationInfo location;
    private Context context;

    @Inject
    public IotPushPresenter(Context context, DataManager dataManager) {
        this.dataManager = dataManager;
        this.context = context;
        connectEvent = new ConnectEvent();
        receiver = new ClientReceiver();
        appId = "9092c4ee91ee49d6870cc7c1900d907e";
        appSecret = "3eae59ff3d8142bdb8b4e2f06f1fcd19";
        clientId = DeviceUtils.getAndroidID(context);
        tags = new ArrayList<>();
        groups = new ArrayList<>();
    }

    @Override
    public void attachView(V v) {
        super.attachView(v);
        EventBus.getDefault().register(this);
    }

    @Override
    public void detachView() {
        super.detachView();
        EventBus.getDefault().unregister(this);
    }

    public Message initMessage(LocationInfo locationInfo, String clientId, String appId) {
        Message message = new Message();
        message.setAudience(getAudience());
        message.setMetaInfo(getMetaInfo(locationInfo, clientId, appId));
        String msg = JsonUtils.stringify(message);
        Log.e("msg111 = ", msg);
        return message;
    }

    public MetaInfo getMetaInfo(LocationInfo locationInfo, String clientId, String appId) {
        MetaInfo metaInfo = new MetaInfo();
        metaInfo.setContentType("text/plain");
        metaInfo.setContent(getContent(locationInfo, clientId, appId));
        return metaInfo;
    }

    public Audience getAudience() {
        Audience audience = new Audience();
        audience.setTags("$SYS$");
        audience.setType(ClientTypeEnum.TAGS);
        return audience;
    }

    public String getContent(LocationInfo locationInfo, String clientId, String appId) {
        PushContent content = new PushContent();
        PushContent.BodyBean.LocationBean locationBean = content.getBody().getLocation().setProvinceName(locationInfo.getProvince())
                .setCityName(locationInfo.getCity()).setAreaName(locationInfo.getDistrict())
                .setAddress(locationInfo.getAddress())
                .setLon(locationInfo.getLongitude())
                .setLat(locationInfo.getLatitude());
        PushContent.BodyBean.AppVOBean appVOBean = content.getBody().getAppVO()
                .setAppName(AppUtils.getAppName(context))
                .setAppId(appId);
        content.setAction("DeviceUpload");


        content.getBody()
                .setLocation(locationBean)
                .setAppVO(appVOBean)
                .setOpType("ANDROID")
                .setClientId(clientId)
                .setDeviceModel(DeviceUtils.getModel())//设备型号
                .setManufacturers(DeviceUtils.getManufacturer())//设备厂商
                .setNetwork(NetworkUtils.getNetworkTypeName(context))
                .setAlias(alias)
                .setTags(tags)
                .setGroups(groups)
                .setOpVersion(DeviceUtils.getOpVersion());//操作系统版
        String body = JsonUtils.stringify(content.getBody());
        JSONObject json = new JSONObject();
        try {
            json.put("action", "DeviceUpload");
            json.put("body", body);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json.toString();
    }

    public void initPush(final LocationInfo locationInfo) {
        location = locationInfo;
        Log.e("clientId=", clientId);
        try {
            IoTCommunicationClient.connect(appId, appSecret, clientId, receiver, connectEvent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //设置标签、别名
    public void setTagsAlias(final String tags, final String alias) {
        try {
            if (tags != null) {
                String[] cd = tags.split(",");
                for (int i = 0; i < cd.length; i++) {
                    this.tags.add(cd[i]);
                }

                IoTCommunicationClient.setTags(tags);
            }
            if (alias != null) {
                this.alias = alias;

                IoTCommunicationClient.setAlias(alias);
            }
            IoTCommunicationClient.sendTextMsg(initMessage(location, clientId, appId));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Subscribe
    public void onEvent(MessageEvent MessageEvent) {//初始化的回调
        if (MessageEvent.getMsg().equals("连接成功。")) {//初始化成功开始设备上报
            try {
                IoTCommunicationClient.sendTextMsg(initMessage(location, clientId, appId));
                setTagsAlias("VEHICLE,deviceModel,vm100", null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (MessageEvent.getMsg().equals("连接失败。")) {//初始化失败，再次初始化
            try {
                IoTCommunicationClient.connect(appId, appSecret, clientId, receiver, connectEvent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 保存消息
     *
     * @param pushMsg
     */
    public void savaPush(PushMsg pushMsg) {
        getCompositeDisposable().add(dataManager.getPushMsgHelper().insertOrUpdate(pushMsg)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe());
    }

    /**
     * 获取消息列表
     */
    public void getMsgList() {
        getCompositeDisposable().add(dataManager.getPushMsgHelper().loadAll()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(pushMsgs -> getMvpView().getMsgList(pushMsgs)));
    }

    /**
     * 删除消息提示
     *
     * @param pushMsg
     */
    public void delete(PushMsg pushMsg) {
        getCompositeDisposable().add(dataManager.getPushMsgHelper().delete(pushMsg)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        getMvpView().showMessage("删除成功");
                        getMsgList();
                    } else {
                        getMvpView().showMessage("删除失败");
                    }
                }));
    }

    /**
     * 清空消息数据
     */
    public void clear() {
        getCompositeDisposable().add(dataManager.getPushMsgHelper().clear()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        getMvpView().showMessage("清空成功");
                        getMsgList();
                    } else {
                        getMvpView().showMessage("清空失败");
                    }
                }));
    }
}
